package com.mdx.order.resolver;
import com.mdx.common.base.CommonResponse;
import com.mdx.order.annotation.CurrentLocalUser;
import com.mdx.order.entity.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

/**
 * 当前用户参数解析器
 */
@Component
public class LoginManagerHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private static final Logger LOG = LoggerFactory.getLogger(LoginManagerHandlerMethodArgumentResolver.class);

    public static final String CURRENT_LOGIN_USER = "user";


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 检查参数是否被 @CurrentLocalUser 注解修饰
        if (parameter.hasParameterAnnotation(CurrentLocalUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) {
            return null;
        }
        //Object user = request.getAttribute(CURRENT_LOGIN_USER);
        // 下面我直接创建了一个用户类，模拟从认证中提取用户信息，大家这里可以从拦截器或者过滤器中拿
        CurrentUser currentUser = new CurrentUser();
        currentUser.setUsername("admin");
        LOG.info("获取到当前用户 = {}", currentUser);
        return currentUser;
    }
}
